import React, { memo,useEffect ,useState} from 'react'
import { useDispatch } from "react-redux";
import { Button, Card,Select,Input,Table, message  } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { saveProductAction } from "@/store/actionCreator";
import { reqProductList,reqProductSearchList,reqProductUpdateStatus } from "@/network";
import { PAGE_SIZE } from "@/common";

const { Option } = Select;

export default memo(function HjProduct(props) {
  //state props
  const [productList, setProductList] = useState([]); //商品列表数据（分页后的）
  const [total, setTotal] = useState(0); //服务器里一共多少条数据
  const [pages, setPages] = useState(0); //一共多少页
  const [current, setCurrent] = useState(1);//当前分页器在第几页
  const [searchType, setSearchType] = useState('productName');//根据商品名称/商品描述搜索的类型
  const [keyWord, setKeyWord] = useState('');//输入框搜索输入的内容
  const [isSearch, setIsSearch] = useState(false);//是否是搜索显示列表数据
  const [isLoading, setIsLoading] = useState(true);//是否在加载中

//  redux hooks
  const dispatch = useDispatch()

const columns = [
  {
    title: '商品名称',
    dataIndex: 'name',
    key: 'name',
    width:'18%',
  },
  {
    title: '商品描述',
    dataIndex: 'desc',
    key: 'desc',
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
    render:price=>'￥'+price
  },
  {
    title: '状态',
    //dataIndex: 'status',
    key: 'status',
    align:'center',
    width:'10%',
    render:(item)=>{
    return (
      <div>
        <Button 
            type="primary" 
            danger={item.status===1?true:false}
            onClick={e=>updateProdStatus(item)}
        >
          {item.status===1?'下架':'上架'}
        </Button><br />
         <span>{item.status===1?'在售':'已停售'}</span>
      </div>
    )
    }
  },
  {
    title: '操作',
    //dataIndex: 'action',
    key: 'action',
    align:'center',
    width:'10%',
    render:item=>{
      return (
        <div>
          <Button type="link" onClick={()=>props.history.push(`/admin/prod/product/detail/${item._id}`)}>详情</Button><br />
          <Button type="link" onClick={()=>props.history.push(`/admin/prod/product/addupdate/${item._id}`)}>修改</Button>
        </div>
      )
    }
  },
];
// 更新上架下架
 const updateProdStatus = async(item)=>{
  //  修改上架下架状态
   let {_id,status} = item
    if(status===1)status=2
    else{status=1}
   const result = await reqProductUpdateStatus(_id,status)
   if(result.status===0){
        // getProductList();
     const  newProductList = productList.map(item =>{
            if(item._id===_id){
              item.status = status
            }
            return item
        })
        setProductList(newProductList)
        message.success('更新成功',1)
      }

   

 }
 const getProductList = async(num=1) =>{
       let result
      if(isSearch) result = await reqProductSearchList(num,PAGE_SIZE,searchType,keyWord) 
      else{
        result = await reqProductList(num,PAGE_SIZE)
      }
      setIsLoading(false)//取消加载中
      const {status,data} = result
      if(status===0){
        setProductList(data.list)
        setTotal(data.total)
        setPages(data.pages)
        setCurrent(num)
        // 保存到redux中
        dispatch(saveProductAction(data))
      }
  }
 
  useEffect(() => {
    // 第一次渲染页面就发请求
    getProductList()
    // eslint-disable-next-line 
  },[]);
   
  // 点击搜索按键触发的函数
  const search = ()=>{
    setIsSearch(true) //我想等他更新后再执行下一行代码。该怎么做啊
    getProductList()
    
  }


  return (
    <div>
      <Card 
          title={  
                <div>
                  <Select 
                    style={{ width: 120 }} 
                    labelInValue
                    defaultValue={{ value: 'productName' }}
                     onChange={value=>setSearchType(value.key)}>
                      <Option value="productName">按名称搜索</Option>
                      <Option value="productDesc">按描述搜索</Option>
                  </Select>
                  <Input 
                     placeholder="关键字" 
                     style={{width:'20%',margin:'0 10px'}}
                     allowClear
                     onChange={e=>setKeyWord(e.target.value)}/>
                  <Button type="primary" onClick={search}>搜索</Button>
                </div>
              } 
          extra={<Button type="primary" onClick={()=>props.history.push("/admin/prod/product/addupdate")} icon={<PlusOutlined  />}>添加商品</Button>}>
     
           <Table 
                  dataSource={productList} 
                  columns={columns} 
                  rowKey="_id"
                  bordered
                  showHeader
                  loading={isLoading}
                   pagination={
                        {
                        pageSize:PAGE_SIZE,
                        defaultCurrent:1,
                        onChange:getProductList,
                        current,
                        total,
                        pages}}
                  />;
     
      </Card>
    </div>
  )
})
